package PhotoVoltaic.UI;
import PhotoVoltaic.Equipment.BaseEquip;
import PhotoVoltaic.Equipment.Combiner;
import PhotoVoltaic.Equipment.Inverter;
import PhotoVoltaic.Manager.manager;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.*;
import java.util.Vector;

import static java.lang.Integer.parseInt;

public class Back_end {
	//load the UI
	Front_end UI = new Front_end("光伏发电系统");
	//load the data from the file and give it to the manager
	manager m = new manager();
	Inverter inverter;
	Combiner combiner;
	String name, status, type;
	int involt, outvolt, outpower, tolcur, tolvol;
	String filepath = "./equipment.txt";
	Back_end() {
		//initialize the table and store the data using manager
		File file = new File("./equipment.txt");
		try (BufferedReader br = new BufferedReader(new FileReader(filepath))) {
			String line;
			while ((line = br.readLine()) != null) {
				String[] rowData = line.split(",");  // split the components
				if ("Inverter".equals(rowData[0])) { //if the type is inverter
					inverter = new Inverter(rowData[2],rowData[3],Integer.parseInt(rowData[4]),Integer.parseInt(rowData[5]),Integer.parseInt(rowData[6]));
					m.EquipHub.add(inverter);
					m.Equipname.add(inverter.getname());
				} else if ("conbiner".equals(rowData[0])) {
					combiner = new Combiner(rowData[2],rowData[3],Integer.parseInt(rowData[4]),Integer.parseInt(rowData[5]));
					m.EquipHub.add(combiner);
					m.Equipname.add(combiner.getName());
				}
				UI.vdata.add(rowData); //add the data into the table
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		//implement the add button function
		UI.add_b.addActionListener(e->{
			//if the name of the equiipment is already in the manager, then return
			if (m.Equipname.contains(UI.name_t.getText())) {
				//clear out the textfield
				UI.name_t.setText("");
				//pop out to inform the user
				JOptionPane.showMessageDialog(null, "该设备已存在,请重新输入", "提示", JOptionPane.ERROR_MESSAGE);
			} else {
				//judge the type of the equipment
				for(Component c:UI.b_panel.getComponents()){
					if(c instanceof JRadioButton){
						if(((JRadioButton) c).isSelected()){
							type = ((JRadioButton)c).getText();
						}
					}
				}
				if ("逆变器".equals(type)) {
					//get user input and put it into the manager
					name = UI.name_t.getText();
					status = UI.status_t.getText();
					involt = Integer.parseInt(UI.inVolt_t.getText());
					outvolt = Integer.parseInt(UI.outVolt_t.getText());
					outpower = Integer.parseInt(UI.outPower_t.getText());
					inverter = new Inverter(name,status,involt,outvolt,outpower);
					m.Equipname.add(inverter.getname());
					m.EquipHub.add(inverter);
					//add the data into the table
					UI.vdata.add(new String[]{inverter.getType(),inverter.getID(),inverter.getName(),inverter.getStatus(),String.valueOf(inverter.get_inVolt()),String.valueOf(inverter.get_outVolt()),String.valueOf(inverter.get_outPower())});
					//update the table
					UI.Equip_Table.updateUI();
					//create a file stream to write data into the file
					try {
						FileWriter fileWriter = new FileWriter(filepath,true);
						fileWriter.write(inverter.getType()+","+inverter.getID()+","+inverter.getName()+","+inverter.getStatus()+","+String.valueOf(inverter.get_inVolt())+","+String.valueOf(inverter.get_outVolt())+","+String.valueOf(inverter.get_outPower())+"\n");
						fileWriter.flush();
						fileWriter.close();
					} catch (IOException ex) {
						throw new RuntimeException(ex);
					}
				}else if ("汇流箱".equals(type)) {
					//get user input and put it into the manager
					name = UI.name_t.getText();
					status = UI.status_t.getText();
					tolvol = Integer.parseInt(UI.tol_Volt_t.getText());
					tolcur = Integer.parseInt(UI.tol_Cur_t.getText());
					combiner = new Combiner(name,status,tolvol,tolcur);
					m.Equipname.add(combiner.getName());
					m.EquipHub.add(combiner);
					//add the data into the table
					UI.vdata.add(new String[]{combiner.getType(),combiner.getID(),combiner.getName(),combiner.getStatus(),String.valueOf(combiner.getVolt()),String.valueOf(combiner.getCur())});
					//create a file stream to write data into the file
					try {
						FileWriter fileWriter = new FileWriter(filepath,true);
						fileWriter.write(combiner.getType()+","+combiner.getID()+","+combiner.getName()+","+combiner.getStatus()+","+String.valueOf(combiner.getVolt())+","+String.valueOf(combiner.getCur())+"\n");
						fileWriter.flush();
						fileWriter.close();
					} catch (IOException ex) {
						throw new RuntimeException(ex);
					}
					//clear out the textfield
					UI.name_t.setText("");
				} else {
					//pop out to inform the user
					JOptionPane.showMessageDialog(null, "请选择设备类型", "提示", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		//implement the delete function
		UI.delete_b.addActionListener(e->{
			name = UI.name_t.getText();//the name of the equipment to be deleted
			try {
				FileWriter fileWriter = new FileWriter(filepath); //create a file stream to read data from the file
				fileWriter.write(""); //delete the origin data
				//delete the data from the manager
				for (int i = 0; i < UI.vdata.size(); i++) {
					if (UI.Equip_Table.isRowSelected(i)) {
						int columnCount = UI.Equip_Table_model.getColumnCount(); // 获取列数
						Object[] rowData = new Object[columnCount];
						for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
							rowData[columnIndex] = UI.Equip_Table_model.getValueAt(i, columnIndex);
							//read the data as object and store them into the manager
							if ("逆变器".equals(rowData[0])) {
								inverter = new Inverter(rowData[2].toString(),rowData[3].toString(),Integer.parseInt(rowData[4].toString()),Integer.parseInt(rowData[5].toString()),Integer.parseInt(rowData[6].toString()));
								m.EquipHub.add(inverter);
								m.Equipname.add(inverter.getname());
							} else if ("汇流箱".equals(rowData[0])) {
								combiner = new Combiner(rowData[2].toString(),rowData[3].toString(),Integer.parseInt(rowData[4].toString()),Integer.parseInt(rowData[5].toString()));
								m.EquipHub.add(combiner);
								m.Equipname.add(combiner.getName());
							}
						}
					}
				}
				//rewrite the data
				fileWriter.flush();
				fileWriter.close();
			}catch (IOException ex) {
				ex.printStackTrace();
			}
		});
		//implement the query function
		UI.query_b.addActionListener(e->{
			try {
				//bufferedreader to read the data from the file
				BufferedReader br = new BufferedReader(new FileReader(filepath));
				//read by line and judge the type of the equipment by the first element
				String line;
				while ((line = br.readLine()) != null) {
					String[] rowData = line.split(",");  // split the components
					if ("逆变器".equals(rowData[0])) { //if the type is inverter
						inverter = new Inverter(rowData[2],rowData[3],Integer.parseInt(rowData[4]),Integer.parseInt(rowData[5]),Integer.parseInt(rowData[6]));
						m.EquipHub.add(inverter);
						m.Equipname.add(inverter.getname());
					} else if ("汇流箱".equals(rowData[0])) {
						combiner = new Combiner(rowData[2],rowData[3],Integer.parseInt(rowData[4]),Integer.parseInt(rowData[5]));
						m.EquipHub.add(combiner);
						m.Equipname.add(combiner.getName());
					}
				}
				//find the equipment by the name
				for (BaseEquip baseEquip : m.EquipHub) {
					if (baseEquip.getname().equals(UI.name_t.getText())) {
						//if the equipment is found, then load the data into the table
						UI.vdata.add(new String[]{baseEquip.getType(),baseEquip.getID(),baseEquip.getName(),baseEquip.getStatus()});
					}
				}
			}catch (IOException ex) {
				ex.printStackTrace();
			}
		});
	}
	public static void main(String args[]) {
		new Back_end();
	}
}
